package com.ck.controller;

import com.ck.util.JwtUtil;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

@RestController
public class HelloWorldController {
    @GetMapping("/api/admin")
    @PreAuthorize("hasAuthority('ROLE_ADMIN')")
    public @ResponseBody
    Object helloToAdmin(String userId) {
        return "Hello World! You are ADMIN ";
    }

    @GetMapping("/api/hello")
    public @ResponseBody
    Object hello(String userId) {
        return "Hello World! You have valid token";
    }

    @GetMapping("/api/getUserInfo")
    public Object getUserInfo(HttpServletRequest request){
        return JwtUtil.validateTokenAndGetClaims(request);
    }

    @PostMapping("/login")
    public Object login(HttpServletResponse response,
                        @RequestBody Account account) throws IOException {
        if (isValidPassword(account)) {
            String jwt = JwtUtil.generateToken(account.username);
            return new HashMap<String, String>() {{
                put("token", jwt);
            }};
        } else {
            return HttpStatus.UNAUTHORIZED;
        }
    }


    private boolean isValidPassword(Account ac) {
        ac = new Account();
        ac.setUsername("13242967410");
        ac.setPassword("123456");
        //we just have 2 hardcoded user
        if ("13242967410".equals(ac.username) && "123456".equals(ac.password)
                || "user".equals(ac.username) && "user".equals(ac.password)) {
            return true;
        }
        return false;
    }


    public static class Account {
        public String username;
        public String password;

        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }
    }
}
